<?php
/**
*
* @package phpBB3
* @version $Id$
* @copyright (c) 2010
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/	
	
 
define('IN_PHPBB', true);
$phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : './';
$phpEx = substr(strrchr(__FILE__, '.'), 1);
include_once($phpbb_root_path . 'common.' . $phpEx);
include_once($phpbb_root_path . 'sv_common.' . $phpEx);
include_once($phpbb_root_path . 'prophet_common.' . $phpEx);



// output HTTP header
$today = get_date_from_time(get_taiwan_time());	

header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=$today.csv");
header("Pragma: no-cache");
header("Expires: 0");

//$debug = true;

get_TWSE_data();

get_international_index_from_Yahoo();

gen_report();





function get_international_index_from_Yahoo()
{
	global $db, $debug;
	global $year_set, $month_set, $day_set;

	if ($debug)
		echo "get_international_index_from_Yahoo - begin\n";
			
	get_index_from_Yahoo('index_cac40', 	'%5EFCHI');
//	get_index_from_Yahoo('index_dji', 		'%5EDJI');
	get_index_from_Yahoo('index_ftse100', 	'%5EFTSE');
	get_index_from_Yahoo('index_hangseng', 	'%5EHSI');
	get_index_from_Yahoo('index_nasdaq', 	'%5EIXIC');
	get_index_from_Yahoo('index_shanghai', 	'000001.SS');
	get_index_from_Yahoo('index_sp500', 	'%5EGSPC');
	get_index_from_Yahoo('index_gdaxi', 	'%5EGDAXI');
	get_index_from_Yahoo('index_nikkei', 	'%5EN225');
	
	get_index_from_Yahoo('interest_rate_10_year_cboe', 	'%5ETNX', true);
	
	
	return;
}

// get figures from Yahoo! Finance. For interest rates, $volume_can_be_zero should be set to true since the volume is always zero.
function get_index_from_Yahoo($table_name, $symbol_in_yahoo, $volume_can_be_zero = false)
{
	global $db, $debug;
	
	if ($debug)
		echo "get_index_from_Yahoo, $table_name, $symbol_in_yahoo  - begin\n";
		
	$today = get_date_from_time(get_taiwan_time());	
	if ($debug)
		echo "today: $today\n";
		
	$last_date	= '';
	$query 		= 'SELECT * from ' . $table_name . ' ORDER BY date DESC';
	$result		= $db->sql_query_limit($query, 1);
	if ($row = $db->sql_fetchrow($result))
	{
		$last_date = $row['Date'];
		if ($debug)
			echo "last_date: $last_date\n";
	}
	
	if (strcmp($last_date, $today) >= 0 )
		return;
		
	
		// query Yahoo! Finance		
		$from_y = get_year_from_date($last_date);
		$from_m = (int)(get_month_from_date($last_date)) - 1;
		$from_d = get_day_from_date($last_date);
		$to_y	= get_year_from_date($today);
		$to_m	= (int)(get_month_from_date($today)) - 1;
		$to_d	= get_day_from_date($today);
		
		$url = "http://ichart.finance.yahoo.com/table.csv?s=$symbol_in_yahoo&a=$from_m&b=$from_d&c=$from_y&d=$to_m&e=$to_d&f=$to_y&g=d&ignore=.csv";
		if ($debug)
			echo "$url \n";
		
		$raw_file = file_get_contents($url);
    	if ($raw_file == false)
    		return '';
	
    	$csv 		= sv_str_getcsv ($raw_file, "\n");    
    	//print_r($csv);
    
    	foreach($csv as &$row)
    	{
	    	$row = sv_str_getcsv($row[0]);
	    	if (sizeof($row[0]) != 7)
	    		continue;
    
	    	if ($debug)
	    		print_r($row[0]);	  
	    	
	    	$q_date 	= $row[0][0];
	    	$q_open 	= $row[0][1];
	    	$q_high 	= $row[0][2];
	    	$q_low 		= $row[0][3];
	    	$q_close 	= $row[0][4];
	    	$q_volume 	= $row[0][5];
	    	$q_adj_close= $row[0][6];
	    
	    	if ($q_date == '' || strlen($q_date) != 10)
	    		continue;	    		
	    	if ($volume_can_be_zero == false && $q_volume == 0)
	    		continue;
	    	
	    	$q_date = get_date_from_Yahoo_date($q_date);
	    		
	    	if ($debug)
	    		echo "$q_date\n";
	    		
	    	// check if the record already exist	
	    	$query 		= 'SELECT * from  ' . $table_name . '  WHERE date="' . $q_date . '"';
			$result		= $db->sql_query_limit($query, 1);
			
			if ($debug)
	    		echo "$query\n";
	    		
			if ($row = $db->sql_fetchrow($result))
			{
				if ($debug)
					echo "the record for $q_date already exist \n";
					
				continue;
			}
		
			// add new records.
			$sql = 'INSERT INTO  ' . $table_name . '  (Date, Open, High, Low, Close, Volume, `Adj Close`) VALUES ("' . $q_date . '" ,' .  $q_open . ' ,' . $q_high . ' ,' . $q_low . ' ,' . $q_close . ' ,' . $q_volume . ' ,' . $q_adj_close .	')';
    		if ($debug)
	    		echo "$sql\n";
			$db->sql_query($sql);			
    	}
	
}

// get date (format: YYYYMMDD) from Yahoo date (format: YYYY-MM-DD)
function get_date_from_Yahoo_date($yahoo_date)
{
	if (strlen($yahoo_date) != 10)
		return '';
		
	$y = substr($yahoo_date, 0, 4);
	$m = substr($yahoo_date, 5, 2);
	$d = substr($yahoo_date, 8, 2);
	
	return $y.$m.$d;
}

function get_TWSE_data($only_add_new_record = true)
{
	global $db, $debug;
	global $year_set, $month_set, $day_set;

	if ($debug)
		echo "get_TWSE_data - begin\n";
	
	// don't go over today.
	$today = get_date_from_time(get_taiwan_time());	
	if ($debug)
		echo "today: $today\n";
			
	$last_date	= '';
	$query 		= 'SELECT * from taiex_index_volume ORDER BY date DESC';
	$result		= $db->sql_query_limit($query, 1);
	if ($row = $db->sql_fetchrow($result))
	{
		$last_date = $row['date'];
		if ($debug)
				echo "last_date: $last_date\n";
	}
	
	foreach ($year_set as $y)
	{
		foreach ($month_set as $m)
		{
			foreach ($day_set as $d)
			{	
				$date = $y . $m . $d;				
				
				if ($only_add_new_record)
				{
					// skip old records.
					if (strcmp($date, $last_date) <=0 )
						continue;						
				}
				
				// don't go over today.
				if (strcmp($date, $today) >0 )
						break;						

				get_index_volume($y, $m, $d);				
			}
		}		
	}
		
	$last_date	= '';
	$query 		= 'SELECT * from margin_transaction_summary ORDER BY date DESC';
	$result		= $db->sql_query_limit($query, 1);
	if ($row = $db->sql_fetchrow($result))
	{
		$last_date = $row['date'];
		if ($debug)
			echo "margin_transaction_summary - last_date: $last_date\n";
	}
	
	foreach ($year_set as $y)
	{
		foreach ($month_set as $m)
		{
			foreach ($day_set as $d)
			{	
				$date = $y . $m . $d;				
				
				if ($only_add_new_record)
				{
					// skip old records.
					if (strcmp($date, $last_date) <=0 )
						continue;						
				}
				
				// don't go over today.
				if (strcmp($date, $today) >0 )
						break;						

				get_short_marginal_sale($y, $m, $d);
			}
		}		
	}
		
	return;
}

// Get the TAIEX index of a specific date. 
function get_index_volume($y, $m, $d)
{
	global $db, $debug;
	
	$date = $y . $m . $d;			
	
	// search from database.
	$query	= "select * from taiex_index_volume where date=$date"; 
	$result	= $db->sql_query_limit($query, 1); 
	if( ($row = $db->sql_fetchrow($result)))
	{
//		echo "index at $date alrady exist\n";
		return ;
	}	
	
	
	$url = "http://www.twse.com.tw/ch/trading/exchange/FMTQIK/FMTQIK2.php?STK_NO=&myear=$y&mmon=$m&type=csv";
	//echo $url;
	
    $raw_file = file_get_contents($url);
    if ($raw_file == false)
    	return '';
	
    $csv 		= sv_str_getcsv ($raw_file, "\n");    
    //print_r($csv);
    
    foreach($csv as &$row)
    {
	    $row = sv_str_getcsv($row[0]);
	    if (sizeof($row[0]) != 6)
	    	continue;
    
	    //print_r($row[0]);
	    	     
	    $q_date 	= $row[0][0];
	    $q_volume 	= $row[0][2];
	    $q_index 	= $row[0][4];
	    
	    if ($q_date == '')
	    	continue;
	    	 
//	    echo "$q_date, $q_volume, $q_index\n";	    	       
	    
		$y = substr($q_date, 0, strlen($q_date) -6);
		$m = substr($q_date, strlen($q_date) - 5, 2);
		$d = substr($q_date, strlen($q_date) - 2, 2);
    		
    	$y = (int)($y) + 1911;
    	$i_date = '' . $y . $m . $d;
    		
    	$query	= "select * from taiex_index_volume where date=$i_date"; 
		$result	= $db->sql_query_limit($query, 1); 
		if( ($row = $db->sql_fetchrow($result)))
		{
//			echo "index/volume at $i_date alrady exist\n";
			continue;
		}	 
		
    	$q_index = ereg_replace("[^0-9.]", "", $q_index); 			
    	$i_closing_index = (float)($q_index);
    		
    	$i_volume = ereg_replace("[^0-9]", "", $q_volume);
    	
    	// from 20080701, volume base is changed from 1000 to 1.
    	if (strcmp($i_date, '20080701' ) < 0)
    		$i_volume = $i_volume * 1000;
    	    	
    	// insert the index record into the database.
    	$sql = 'INSERT IGNORE INTO taiex_index_volume SET date="' . $i_date . '", closing_index=' . $i_closing_index . ', volume=' . $i_volume;
		if ($debug)
    	    	echo "    $sql\n";
    	$result	= $db->sql_query($sql);    		
	}
	
    return '';		
}

function get_short_marginal_sale($y, $m, $d)
{
	global $db, $debug;
	
	$date = $y . $m . $d;			
	
	// search from database.
	$query	= "select * from margin_transaction_summary where date=$date"; 
	$result	= $db->sql_query_limit($query, 1); 
	if( ($row = $db->sql_fetchrow($result)))
	{
//		echo "short and marginal info at $date alrady exist\n";
		return ;
	}	
	
				// get marginal and short info.
				$q = "http://www.twse.com.tw/en/trading/exchange/MI_MARGN/MI_MARGN_2.php?select2=MS&input_date=$y/$m/$d&type=csv";
    			
    			$ch = curl_init($q);
				curl_setopt($ch, CURLOPT_HEADER, 0);
//				curl_setopt($ch, CURLOPT_GET, 1);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
				$output = curl_exec($ch);       
				curl_close($ch);			
				
				if ($output == '')
				{
//					echo "fail to get short and marginal info at $date \n";
					return;
				}
				//echo $output;
								
				$csv 		= sv_str_getcsv ($output, "\n");
    
				//print_r($csv);
				
				$row = sv_str_getcsv($csv[2][0]);
				//print_r($row);
				
				$purchase_on_margin_new 				= ereg_replace("[^0-9]", "", $row[0][1]);
				$purchase_on_margin_redemption 			= ereg_replace("[^0-9]", "", $row[0][2]);
				$purchase_on_margin_outstanding 		= ereg_replace("[^0-9]", "", $row[0][3]);
				$purchase_on_margin_yesterday_remain 	= ereg_replace("[^0-9]", "", $row[0][4]);
				$purchase_on_margin_today_remain	 	= ereg_replace("[^0-9]", "", $row[0][5]);
				
				//echo "$purchase_on_margin_new, $purchase_on_margin_redemption, $purchase_on_margin_outstanding, $purchase_on_margin_yesterday_remain, $purchase_on_margin_today_remain \n";
				
				$row = sv_str_getcsv($csv[4][0]);
				//print_r($row);
				
				$short_sale_redemption 			= ereg_replace("[^0-9]", "", $row[0][1]);
				$short_sale_new 				= ereg_replace("[^0-9]", "", $row[0][2]);
				$short_sale_outstanding 		= ereg_replace("[^0-9]", "", $row[0][3]);
				$short_sale_yesterday_remain 	= ereg_replace("[^0-9]", "", $row[0][4]);
				$short_sale_today_remain	 	= ereg_replace("[^0-9]", "", $row[0][5]);
				
				//echo "$short_sale_redemption, $short_sale_new, $short_sale_outstanding, $short_sale_yesterday_remain, $short_sale_today_remain \n";
				
				$row = sv_str_getcsv($csv[6][0]);
				//print_r($row);
				
				$purchase_on_value_margin_new 				= ereg_replace("[^0-9]", "", $row[0][1]);
				$purchase_on_value_margin_redemption 		= ereg_replace("[^0-9]", "", $row[0][2]);
				$purchase_on_value_margin_outstanding 		= ereg_replace("[^0-9]", "", $row[0][3]);
				$purchase_on_value_margin_yesterday_remain 	= ereg_replace("[^0-9]", "", $row[0][4]);
				$purchase_on_value_margin_today_remain	 	= ereg_replace("[^0-9]", "", $row[0][5]);
				
				//echo "$purchase_on_value_margin_new, $purchase_on_value_margin_redemption, $purchase_on_value_margin_outstanding, $purchase_on_value_margin_yesterday_remain, $purchase_on_value_margin_today_remain \n";
    	
		    			
				$sql = 'INSERT IGNORE INTO margin_transaction_summary (date, 
									purchase_on_margin_new, purchase_on_margin_redemption, purchase_on_margin_outstanding, purchase_on_margin_yesterday_remain, purchase_on_margin_today_remain, 
									short_sale_redemption, short_sale_new, short_sale_outstanding, short_sale_yesterday_remain, short_sale_today_remain,
									purchase_on_value_margin_new, purchase_on_value_margin_redemption, purchase_on_value_margin_outstanding, purchase_on_value_margin_yesterday_remain, purchase_on_value_margin_today_remain
									) VALUES (
									"' . $date . '" ,
									' . $purchase_on_margin_new . ' ,
									' . $purchase_on_margin_redemption . ' ,
									' . $purchase_on_margin_outstanding . ' ,
									' . $purchase_on_margin_yesterday_remain . ' ,
									' . $purchase_on_margin_today_remain . ' ,
									' . $short_sale_redemption . ' ,
									' . $short_sale_new . ' ,
									' . $short_sale_outstanding . ' ,
									' . $short_sale_yesterday_remain . ' ,
									' . $short_sale_today_remain . ' ,
									' . $purchase_on_value_margin_new . ' ,
									' . $purchase_on_value_margin_redemption . ' ,
									' . $purchase_on_value_margin_outstanding . ' ,
									' . $purchase_on_value_margin_yesterday_remain . ' ,
									' . $purchase_on_value_margin_today_remain . ' 
									)';

				if ($debug)
					echo $sql;
    			$db->sql_query($sql);
    			
}


function gen_report()
{
	global $db, $debug;
	global $year_set, $month_set, $day_set;
	
	// print csv header.
	echo 'date, TAIEX, volume, purchase_on_margin_new, purchase_on_margin_redemption, purchase_on_margin_outstanding, purchase_on_margin_yesterday_remain, purchase_on_margin_today_remain, short_sale_redemption, short_sale_new, short_sale_outstanding, short_sale_yesterday_remain,	short_sale_today_remain, purchase_on_value_margin_new, purchase_on_value_margin_redemption, purchase_on_value_margin_outstanding, purchase_on_value_margin_yesterday_remain, purchase_on_value_margin_today_remain, date_cac40, cac40, date_dji, dji, date_ftse100, ftse100, date_hangseng, hangseng, date_nasdaq, nasdaq, date_nikkei, nikkei, date_shanghai, shanghai, date_sp500, sp500, date_cboe_10year_rate, cboe_10year_rate, buy_sell_signal';
	echo "\n";
	
	$taiex		= array();
	
	// Get all TAIEX before calculating Moving Average. 
	foreach ($year_set as $y)
	{
		foreach ($month_set as $m)
		{
			foreach ($day_set as $d)
			{
				// get index
				$date = $y . $m . $d;			
				$sql 	= 'SELECT * FROM taiex_index_volume WHERE date="' . $date . '"';
				$result = $db->sql_query_limit($sql, 1); 
				if ($r = $db->sql_fetchrow($result))
				{						
					$taiex[] = $r['closing_index'];
				}	

			} //foreach ($day_set as $d)		
		} //foreach ($month_set as $m)
	} //foreach ($year_set as $y)	
	
	$i 		= 0;
	$peak	= array();
	
	while( $i < sizeof($taiex))
	{
		$peak[]		= 0;
		++$i;
	}
	
	$i = 0;
	$window	= 420;
	$step	= $window/3;
	
	while( $i + $window < sizeof($taiex))
	{
		$j = get_max($taiex, $i, $window);
		$peak[$j] = 1;

		$j = get_min($taiex, $i, $window);
		$peak[$j] = -1;
		
		$i = $i + $step;
	}
	
	// make fuzzy backward
	$fuzzy		= 20;		// checking the 20 days before.
	$tolerance 	= 0.1;		// if the difference is within the tolerance range, include it. 
	
	$i 		= $fuzzy;
	while( $i < sizeof($taiex))
	{
		if ($peak[$i] == 1 || $peak[$i] == -1)
		{
			$j = 0;
			
			while($j < $fuzzy)
			{
				if (abs($taiex[$i - $j] - $taiex[$i]) < $tolerance * $taiex[$i])
				{
					$peak[$i - $j] = $peak[$i];
				}
				else
					break;
				
				++$j;
			}
		}
		
		++$i;
	}
	
	// make fuzzy forward
	$fuzzy	= 20;
	$i 		= 0;
	while( $i + $fuzzy < sizeof($taiex))
	{
		if ($peak[$i] == 1 || $peak[$i] == -1)
		{
			$j = 0;
			
			while($j < $fuzzy)
			{
				if (abs($taiex[$i + $j] - $taiex[$i]) < $tolerance * $taiex[$i])
				{
					$peak[$i + $j] = $peak[$i];
				}
				else
					break;					
				
				++$j;
			}
		}
		
		$i += $fuzzy;
	}
		
	
	// create international index array.	
	$index_cac40	= array();
	$index_dji		= array();
	$index_ftse100	= array();	
	$index_hangseng	= array();
	$index_nasdaq	= array();
	$index_nikkei	= array();
	$index_shanghai	= array();
	$index_sp500	= array();
	
	$cboe_10year_rate	= array();
	
	// don't go over today.
	$today = get_date_from_time(get_taiwan_time());	
	
	$i = 0;
	// Retrieve data from database and write out report.  
	foreach ($year_set as $y)
	{
		foreach ($month_set as $m)
		{
			foreach ($day_set as $d)
			{
				$date = $y . $m . $d;			
				
				// don't go over today.
				if (strcmp($date, $today) >0 )
					break;
				
				// get index volume (only the days with index and volume)
				$sql 	= 'SELECT * FROM taiex_index_volume WHERE date="' . $date . '"';
				$result = $db->sql_query_limit($sql, 1); 
				if ($r = $db->sql_fetchrow($result))
				{						
					echo $date . ', ';
					
					echo $r['closing_index'] . ', ';
					echo $r['volume'] . ', ';

					// get short & marginal info.
					$sql 	= 'SELECT * FROM margin_transaction_summary WHERE date="' . $date . '"';
					$result = $db->sql_query_limit($sql, 1); 
					if ($r = $db->sql_fetchrow($result))
					{		
						$twse_data = $r;
										
							echo $twse_data['purchase_on_margin_new'] . ', ';
							echo $twse_data['purchase_on_margin_redemption'] . ', ';				echo $twse_data['purchase_on_margin_outstanding'] . ', ';
							echo $twse_data['purchase_on_margin_yesterday_remain'] . ', ';			echo $twse_data['purchase_on_margin_today_remain'] . ', ';
							echo $twse_data['short_sale_redemption'] . ', ';						echo $twse_data['short_sale_new'] . ', ';
							echo $twse_data['short_sale_outstanding'] . ', ';						echo $twse_data['short_sale_yesterday_remain'] . ', ';					
							echo $twse_data['short_sale_today_remain'] . ', ';						echo $twse_data['purchase_on_value_margin_new'] . ', ';
							echo $twse_data['purchase_on_value_margin_redemption'] . ', ';			echo $twse_data['purchase_on_value_margin_outstanding'] . ', ';
							echo $twse_data['purchase_on_value_margin_yesterday_remain'] . ', ';	echo $twse_data['purchase_on_value_margin_today_remain'] . ', ';
							
					}
					
					// output international index
					print_index($index_cac40);
					print_index($index_dji);
					print_index($index_ftse100);
					print_index($index_hangseng);
					print_index($index_nasdaq);
					print_index($index_nikkei);
					print_index($index_shanghai);
					print_index($index_sp500);	
					print_index($cboe_10year_rate);			

					
					
					//echo $pma[$i] . ', ';
					//echo $cma[$i] . ',';
					//echo $sig_buy[$i] . ', ';
					//echo $sig_sell[$i] . ', ';
					echo $peak[$i] . ', ';
					//echo $valley[$i] . ', ';
					++$i;					
					
					echo "\n";				
				}
				
				// get international index data
				$r = get_international_index($date, 'index_cac40');
				if ($r != false)
					$index_cac40 = $r;				
							
				$r = get_international_index($date, 'index_dji');
				if ($r != false)
					$index_dji = $r;
								
				$r = get_international_index($date, 'index_ftse100');
				if ($r != false)
					$index_ftse100 = $r;
									
				$r = get_international_index($date, 'index_hangseng');
				if ($r != false)
					$index_hangseng = $r;
				
				$r = get_international_index($date, 'index_nasdaq');
				if ($r != false)
					$index_nasdaq = $r;
									
				$r = get_international_index($date, 'index_nikkei');
				if ($r != false)
					$index_nikkei = $r;
									
				$r = get_international_index($date, 'index_shanghai');
				if ($r != false)
					$index_shanghai = $r;
								
				$r = get_international_index($date, 'index_sp500');
				if ($r != false)
					$index_sp500 = $r;
								
				$r = get_international_index($date, 'interest_rate_10_year_cboe');
				if ($r != false)
					$cboe_10year_rate = $r;
					
									
				
			} //foreach ($day_set as $d)		
		} //foreach ($month_set as $m)
	} //foreach ($year_set as $y)	
}

function get_international_index($date, $table_name)
{
	global $db, $debug;
	
	$sql 	= 'SELECT * FROM ' . $table_name . ' WHERE Date="' . $date . '"';
	$result = $db->sql_query_limit($sql, 1); 
	if ($r = $db->sql_fetchrow($result))
	{
		//print_r($r);
		return $r;
	}
	
	return false;	
}

function print_index($p)
{
	echo $p['Date'] . ', ';							
//	echo $p['Open'] . ', ';
//	echo $p['High'] . ', ';							
//	echo $p['Low'] . ', ';
	echo $p['Close'] . ', ';						
//	echo $p['Volume'] . ', ';
//	echo $p['Adj Close'] . ', ';								
}

function pre_ma($taiex, $width, $idx)
{
	//echo "pre_ma: width:$width, idx:$idx\n";
	
	if (sizeof($taiex) <= 0 || $idx > sizeof($taiex) || $width <= 0)
		return 0;		
	if (sizeof($taiex) <= $width)
		return sum($taiex)/ sizeof($taiex);
			
	if ($idx < $width)
		return sum($taiex, 0, $idx) / ($idx + 1);
		
	return sum($taiex, $idx - $width + 1, $idx) / $width;	
}

function center_ma($taiex, $width, $idx)
{
	//echo "center_ma: width:$width, idx:$idx\n";
	
	if (sizeof($taiex) <= 0 || $idx > sizeof($taiex) || $width <= 0)
		return 0;		
	if (sizeof($taiex) <= $width)
		return sum($taiex)/ sizeof($taiex);
				
	if ($idx < ($width / 2))
		return sum($taiex, 0, $idx + ($width / 2)) / ($idx + ($width/2) + 1);
		
	if ($idx + ($width / 2) > sizeof($taiex))
		return sum($taiex, $idx - ($width / 2), sizeof($taiex)) / (sizeof($taiex) - $idx + ($width/2));
		
	return sum($taiex, $idx - ($width/2), $idx + ($width/2)) / (($width/2)*2 + 1);	
}

function sum($taiex, $start = 0, $end = -1)
{
	if ($end == -1)
		$end = sizeof($taiex) - 1;
		
	if ($start > $end || sizeof($taiex) == 0 || sizeof($taiex) < $end)
		return 0;
		
	$i = $start;
	$s = 0;
	
	while ($i <= $end)
	{
		$s = $s + $taiex[$i];
		++ $i;
	}
	
	return $s;
}

function get_max($taiex, $i, $window)
{
	$k 		= $i + 1;
	$j		= $i;
	$max	= $taiex[$j];
	
	while ($k < $i + $window)
	{
		if ($taiex[$k] > $max)
		{
			$max = $taiex[$k];
			$j = $k;	
		}
	
		++$k;	
	}
	
	return $j;
}

function get_min($taiex, $i, $window)
{
	$k 		= $i + 1;
	$j		= $i;
	$min		= $taiex[$j];
	
	while ($k < $i + $window)
	{
		if ($taiex[$k] < $min)
		{
			$min = $taiex[$k];
			$j = $k;	
		}
	
		++$k;	
	}
	
	return $j;
}
?>